package org.standard.commons.utils;



import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.StrutsResultSupport;

import com.opensymphony.xwork2.ActionInvocation;

/**
 * result type for output string in action
 * 
 * @author songwei,yaolei <b>Example:</b>
 * 
 * <pre>
 * &lt;!-- START SNIPPET: example --&gt;
 * &lt;result name=&quot;success&quot; type=&quot;string&quot;&gt;
 *   &lt;param name=&quot;stringName&quot;&gt;${info}&lt;/param&gt;
 * &lt;/result&gt;
 * &lt;!-- END SNIPPET: example --&gt;
 * </pre>
 * 
 */
public class StringResultType extends StrutsResultSupport {
	private static final long serialVersionUID = 1L;
	private String contentTypeName;//支持两种格式 plain ,xml
	private String stringName = "";
	private String encoding   ="UTF-8";//default utf-8

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public StringResultType() {
		super();
	}

	public StringResultType(String location) {
		super(location);
	}

	protected void doExecute(String finalLocation, ActionInvocation invocation)
			throws Exception {
		HttpServletResponse response = (HttpServletResponse) invocation
				.getInvocationContext().get(HTTP_RESPONSE);
		String contentType  = conditionalParse(contentTypeName, invocation);
		String encoding_    = conditionalParse(encoding, invocation);
		if (contentType == null) contentType = "plain";
		contentType="text/"+contentType+";charset="+encoding_;
		
		response.setContentType(contentType);
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		PrintWriter out = response.getWriter();
		String result = conditionalParse(stringName, invocation);
		out.println(result);		
		out.flush();
		out.close();
	}

	public String getContentTypeName() {
		return contentTypeName;
	}

	public void setContentTypeName(String contentTypeName) {
		this.contentTypeName = contentTypeName;
	}

	public String getStringName() {
		return stringName;
	}

	public void setStringName(String stringName) {
		this.stringName = stringName;
	}
}
